// 组件自动注册
import Vue from 'vue'

const { upperFirst, camelCase } = require('lodash')

export default class AutoRegisterComponent {
  dealComponentPath(pathList) { // 处理路径,获取对应路径下文件的对象
    const requireComponents = pathList.reduce((pre, curPath) => {
      const component = require.context(curPath, true, /\w+\.vue$/) // 第二个参数为是否查询其子目录
      pre.push(component)
      return pre
    }, [])
    return this.normalizeComponentName(requireComponents)
  }

  normalizeComponentName(componentsInstances) { // 统一组件命名为首字母大写
    componentsInstances.keys().forEach((fileName) => {
      // 获取组件的配置
      const componentConfig = componentsInstances(fileName)

      // 获取组件的 pascalCase 命名
      const componentName = upperFirst(
        camelCase(
          fileName
            .split('/')
            .pop()
            .replace(/\.\w+$/, '')
        )
      )
      return this.registerComponent(componentName, componentConfig)
    })
  }

  registerComponent(name, config) {
    Vue.component(name, config.default || config)
  }
}